// Team 1 Project - Palo Alto Bicycle Club
// Author: Tom Ajayebi
// Class: COIN 71
// Filename: post_ride.js (was bike.js)
// Date Created: 04 March 09
// Purpose:
// 		Send MYSQL query to server side PHP to insert a new group ride row into the the MySQL database.
// Modification History:
//		10 Mar 09 - Vern McGeorge - Renamed to match feature, modified includes to match directory structure, tested, and checked into SVN

// The url of the php servlet that takes an SQL query for the world db and returns an
// XML document with the reply.
var URL = "mysqlQuery.php";
//var URL = "http://ctislab.fhda.edu/ajax/mysqlQuery.php";
var myQUERY = null;
var xmlDoc  =  null;

// Result of INSERT query, just give a message back to user if the insert succeed.
function insertQueryResult(){
    xmlDoc = this.req.responseText;

    //DEBUG: display returned xml for debug
    alert(xmlDoc);
    var resultNode = document.getElementById("AnswerResult");
    document.getElementById("AnswerResult").value = "";
    //displayText("AnswerResult","");
    //resultNode.firstChild.nodeValue += "Answer = " + xmlDoc ;
    //return false;
}

// Result of SELECT query ,give the result back to the calling routine to do whatever they like.
function selectQueryResultXXX(){
    xmlDoc = this.req.responseText;
    //DEBUG: Look at the XML data coming back from server.
    alert(xmlDoc);
    // var resultNode = document.getElementById("AnswerResult");
    var resultNode = document.getElementById("GRSchedule");
    // DEBUG: to display returned result in HTML
    //var myJsonObject=xml2json.parser(xmlDoc);

    // convert returned XML into JSON
    var myJsonObject=xml2json.parser(xmlDoc,'','normal');

    // DEBUG: Display returned result in JSON
    alert(myJsonObject);


    // DEBUG: assign returned JSON to a div on a page for viewing
    // document.getElementById("AnswerResult").innerHTML = myJsonObject;
    resultNode.innerHTML = myJsonObject;
toConsole ("post_ride - selectQueryResult 51");
		var jsonObject = eval("(" + myJsonObject +")");
		// updateRideListing(jsonObject);
toConsole ("post_ride - selectQueryResult 54");
    //displayText("AnswerResult","");
    //resultNode.firstChild.nodeValue += "Answer = " + myJasonObject ;
    //resultNode.firstChild.value = myJasonObject ;

    return false;
}

// construct a SQL query for retriving fields inside mysql.
function viewGroupRidesXXX(){
 //title_value = document.getElementById("viewgroupbutton").firstChild.value  ;
 myQUERY = "q=SELECT id,title,city,start_point,day,date,time,leader,description,photo_url FROM bicycle.rides";

 //call content loader with the query constructed.
 contentLoader = new net.ContentLoader(URL, selectQueryResult, errorFunction, "POST", myQUERY);

}



// Grab user inputed data and INSERT it into mysql DB table
function sendInsertQuery(){
    var title_value = document.getElementById("title").firstChild.value  ;
    var city_value = document.getElementById("city").firstChild.value ;
    var start_point_value = document.getElementById("start_point").firstChild.value ;
    var day_value = document.getElementById("day").firstChild.value ;
    var date_value = document.getElementById("date").firstChild.value ;
    var time_value = document.getElementById("time").firstChild.value ;
    var leader_value = document.getElementById("leader").firstChild.value ;
    var description_value = document.getElementById("description").firstChild.value ;
    var photo_url_value = document.getElementById("photo_url").firstChild.value ;

   //DEBUG:  alert values inputed by user for INSERT Operation
   /*alert("title_value="+title_value+
         "\ncity_value="+city_value+
         "\nstart_point_value="+start_point_value+
         "\nday_value="+day_value+
         "\ndate_value="+date_value+
         "\ntime_value="+time_value+
         "\nleader_value="+leader_value+
         "\ndescription_value="+description_value+
         "\nphoto_url_value="+photo_url_value);
   */

    // Check to see if all the fields are inputed by user.
    if ((title_value == "")  || (city_value == "" )       || (start_point_value == "") ||
        (day_value == "")    || (date_value == "")        || (time_value == "")        ||
        (leader_value == "") || (description_value == "") || (photo_url_value == "")) {
        document.getElementById("AnswerResult").style.color = '#990000' ;
        displayText("AnswerResult","Error: All feilds need to have a value..")
    }
    else {
        myQUERY = "q=INSERT INTO bicycle.rides (title,city,start_point,day,date,time,leader,description,photo_url) VALUES ('"+title_value+"','"+city_value+"','"+start_point_value+"','"+day_value+"','"+date_value+"','"+time_value+"','"+leader_value+"','"+description_value+"','"+photo_url_value+"')";
        contentLoader = new net.ContentLoader(URL, insertQueryResult, errorFunction, "POST", myQUERY);
        displayText("AnswerResult","Success: Record Inserted...");
    }
    return false;
}


// Clear user inputed data
function clearFeilds(){
    document.getElementById("title").firstChild.value="" ;
    document.getElementById("city").firstChild.value="" ;
    document.getElementById("start_point").firstChild.value="" ;
    document.getElementById("day").firstChild.value ="";
    document.getElementById("date").firstChild.value ="";
    document.getElementById("time").firstChild.value ="";
    document.getElementById("leader").firstChild.value ="";
    document.getElementById("description").firstChild.value ="";
    document.getElementById("photo_url").firstChild.value ="";
    removeAllChildrens(document.getElementById("AnswerResult"));
}

function buildTableXXX() {
 var table = document.createElement('table');
table.border = 1;
table.cellPadding = 10;
table.cellSpacing = 2;
var tbody = document.createElement('tbody');
for (var i = 1; i < 10; i++) {
    var row = document.createElement('tr');
    for (var j = 1; j < 10; j++) {
        var cell = document.createElement('td');
        cell.appendChild(document.createTextNode(i + ', ' + j));
        row.appendChild(cell);
    }
    tbody.appendChild(row);
}
table.appendChild(tbody);
document.body.appendChild(table)
}


// called by the ContentLoader when there is an error with the request
function errorFunctionXXX()
{	var answerNode = document.getElementById("Answer");
	answerNode.firstChild.nodeValue += "Error:  DB connection failed : " + this.req.responseText;
}

 /* Sets the name and id attributes of the new node to "nameId".
 * If "text" is present, this also creates a text node with "text" in it and appends it to the new node.
 * Returns the new node.
 * Adapted from page 8 of Crane and Pascarello
 */
function addNode(parent, element, nameId, text) {
  var newNode = document.createElement(element);
  parent.appendChild(newNode);
  newNode.setAttribute("id", nameId);
  newNode.setAttribute("name", nameId);
  if (text != "") {
    var textNode = document.createTextNode(text);
    newNode.appendChild(textNode);
  }
  return newNode;
}


 // this fucntion removes all of parent's children.
function removeAllChildrens(parent) {
  children = parent.childNodes;
  for (var i = children.length-1; i >=0; i--) {
    parent.removeChild(children[i]);
  }
}

 // Add a text to a document. Test a given divId and see if it has children,
 // if not create a Text Node,If it does, then change the text of the child
function displayText(DivId,text){
    var currentNode = document.getElementById(DivId);
    if (!currentNode.hasChildNodes()) {
        var prompt = document.createTextNode(text) ;
        currentNode.appendChild(prompt);
    }
    else {currentNode.firstChild.data  = text;}
}

function setupPage(){
    var parentAnswerNode = document.getElementById("title");
    var titleFeildNode = addNode(parentAnswerNode, "input","title","title");
    titleFeildNode.setAttribute("type", "input");
    titleFeildNode.setAttribute("value", "");
    titleFeildNode.setAttribute("size", 40);
    titleFeildNode.setAttribute("maxlength", 80);

    parentAnswerNode = document.getElementById("city");
    var cityFeildNode = addNode(parentAnswerNode, "input","city","city");
    cityFeildNode.setAttribute("type", "input");
    cityFeildNode.setAttribute("value", "");
    cityFeildNode.setAttribute("size", 30);
    cityFeildNode.setAttribute("maxlength", 30);

    parentAnswerNode = document.getElementById("start_point");
    var start_pointFeildNode = addNode(parentAnswerNode, "input","start_point","start_point");
    start_pointFeildNode.setAttribute("type", "input");
    start_pointFeildNode.setAttribute("value", "");
    start_pointFeildNode.setAttribute("size", 40);
    start_pointFeildNode.setAttribute("maxlength", 80);


    parentAnswerNode = document.getElementById("day");
    var dayFeildNode = addNode(parentAnswerNode, "input","day","day");
    dayFeildNode.setAttribute("type", "input");
    dayFeildNode.setAttribute("value", "");
    dayFeildNode.setAttribute("size", 10);
    dayFeildNode.setAttribute("maxlength", 10);

    parentAnswerNode = document.getElementById("date");
    var dateFeildNode = addNode(parentAnswerNode, "input","date","date");
    dateFeildNode.setAttribute("type", "input");
    dateFeildNode.setAttribute("value", "");
    dateFeildNode.setAttribute("size", 10);
    dateFeildNode.setAttribute("maxlength", 10);

    parentAnswerNode = document.getElementById("time");
    var timeFeildNode = addNode(parentAnswerNode, "input","time","time");
    timeFeildNode.setAttribute("type", "input");
    timeFeildNode.setAttribute("value", "");
    timeFeildNode.setAttribute("size", 10);
    timeFeildNode.setAttribute("maxlength", 10);

    parentAnswerNode = document.getElementById("leader");
    var leaderFeildNode = addNode(parentAnswerNode, "input","leader","leader");
    leaderFeildNode.setAttribute("type", "input");
    leaderFeildNode.setAttribute("value", "");
    leaderFeildNode.setAttribute("size", 30);
    leaderFeildNode.setAttribute("maxlength", 30);

    parentAnswerNode = document.getElementById("description");
    var descriptionFeildNode = addNode(parentAnswerNode, "input","description","description");
    descriptionFeildNode.setAttribute("type", "input");
    descriptionFeildNode.setAttribute("value", "");
    descriptionFeildNode.setAttribute("size", 40);
    descriptionFeildNode.setAttribute("maxlength", 100);

    parentAnswerNode = document.getElementById("photo_url");
    var photo_urlFeildNode = addNode(parentAnswerNode, "input","photo_url","photo_url");
    photo_urlFeildNode.setAttribute("type", "input");
    photo_urlFeildNode.setAttribute("value", "");
    photo_urlFeildNode.setAttribute("size", 40);
    photo_urlFeildNode.setAttribute("maxlength", 80);

    parentAnswerNode = document.getElementById("insertbutton");
    var insertButton = addNode(parentAnswerNode, "button","InsertIntoDB","InsertIntoDB");
    insertButton.setAttribute("type", "button");
    insertButton.setAttribute("value", "InsertIntoDB");
    insertButton.setAttribute("onClick","sendInsertQuery()");

     parentAnswerNode = document.getElementById("clearbutton");
    var clearButton = addNode(parentAnswerNode, "button","clearbutton","Clear Feilds");
    clearButton.setAttribute("type", "button");
    clearButton.setAttribute("value", "clearbutton");
    clearButton.setAttribute("onClick","clearFeilds()");

    parentAnswerNode = document.getElementById("viewgroupbutton");
    var viewgroupbuttonButton = addNode(parentAnswerNode, "button","viewgroupbutton","View Group Rides");
    viewgroupbuttonButton.setAttribute("type", "button");
    viewgroupbuttonButton.setAttribute("value", "viewgroupbutton");
    viewgroupbuttonButton.setAttribute("onClick","viewGroupRides()");
    
    
}

// fucntioned called when admin page first gets loaded.

jQuery.event.add( window, "load", setupPage );
